<template>
  <input @focus="handleFocus" v-clickoutside="handleClose" ref="reference" />
</template>

<script>
import Vue from 'vue';
import Popper from '@/utils/vue-popper';
import merge from '@/utils/merge';
import Clickoutside from '@/utils/clickoutside';

const NewPopper = {
  props: {
    appendToBody: Popper.props.appendToBody,
    offset: Popper.props.offset,
    boundariesPadding: Popper.props.boundariesPadding,
    arrowOffset: Popper.props.arrowOffset
  },
  methods: Popper.methods,
  data() {
    return merge({ visibleArrow: true }, Popper.data);
  },
  beforeDestroy: Popper.beforeDestroy
};

const HAVE_TRIGGER_TYPES = [
  'date',
  'datetime',
  'time',
  'time-select',
  'week',
  'month',
  'year',
  'daterange',
  'monthrange',
  'timerange',
  'datetimerange',
  'dates'
];

const PLACEMENT_MAP = {
  left: 'bottom-start',
  center: 'bottom',
  right: 'bottom-end'
};

export default {
  mixins: [NewPopper],
  props: {
    align: {
      type: String,
      default: 'left'
    }
  },
  directives: {
    clickoutside: Clickoutside
  },
  data() {
    return {
      pickerVisible: false
    };
  },
  watch: {
    pickerVisible(val) {
      if (this.readonly || this.pickerDisabled) return;
      if (val) {
        this.showPicker();
      } else {
        this.hidePicker();
      }
    }
  },
  created() {
    // vue-popper
    this.popperOptions = {
      boundariesPadding: 0,
      gpuAcceleration: false
    };
    this.placement = PLACEMENT_MAP[this.align] || PLACEMENT_MAP.left;

    this.$on('fieldReset', this.handleFieldReset);
  },
  methods: {
    handleClose() {
      if (!this.pickerVisible) return;
      this.pickerVisible = false;
    },
    handleFocus() {
      const type = this.type;
      if (HAVE_TRIGGER_TYPES.indexOf(type) !== -1 && !this.pickerVisible) {
        this.pickerVisible = true;
      }
      this.$emit('focus', this);
    },
    showPicker() {
      if (this.$isServer) return;
      if (!this.picker) {
        this.mountPicker();
      }
      this.pickerVisible = this.picker.visible = true;
      this.updatePopper();
    },
    mountPicker() {
      this.picker = new Vue(this.panel).$mount();
      this.popperElm = this.picker.$el;
      this.$el.appendChild(this.picker.$el);
    },
    hidePicker() {
      if (this.picker) {
        this.pickerVisible = this.picker.visible = false;
        this.destroyPopper();
      }
    }
  }
};
</script>

<style></style>
